package com.github.tommas.admintpl.mybatis;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import java.lang.reflect.Field;
import java.util.Map;

@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class ContextInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        if (SqlCommandType.UPDATE != ms.getSqlCommandType() && SqlCommandType.INSERT != ms.getSqlCommandType()) {
            return invocation.proceed();
        }

        if (!(args[1] instanceof Map)) {
            return invocation.proceed();
        }

        // TODO: cache context param name
        String contextName = null;
        Context context = null;
        if (args[1] instanceof Map) {
            Map<String, Object> params = (Map<String, Object>) args[1];
            for (String k : params.keySet()) {
                Object o = params.get(k);
                if (o instanceof Context) {
                    contextName = k;
                    context = (Context) o;
                    break;
                }
            }
        }

        if (context == null) {
            return invocation.proceed();
        }

        updateMappedStatementIfNeeded(ms, context, contextName);

        return invocation.proceed();
    }

    private void updateMappedStatementIfNeeded(MappedStatement ms, Context context, String contextParam) throws NoSuchFieldException, IllegalAccessException {
        String[] returnColumns = context.getReturnColumns();
        if (returnColumns == null || returnColumns.length == 0) {
            return;
        }

        if (ms.getKeyGenerator() == NoKeyGenerator.INSTANCE) {
            setMappedStatementKeyGenerator(ms);
        }

        String[] keyProps = ms.getKeyProperties();
        if (keyProps == null || keyProps.length == 0) {
            keyProps = new String[returnColumns.length];
            for (int i = 0; i < returnColumns.length; i ++) {
                keyProps[i] = contextParam + "." + returnColumns[i];
            }

            setMappedStatementKeyProperties(ms, keyProps);
            setMappedStatementKeyColumns(ms, returnColumns);
        }
    }

    // HACK: set MappedStatement.keyGenerator with reflection
    private void setMappedStatementKeyGenerator(MappedStatement ms) throws NoSuchFieldException, IllegalAccessException {
        setMappedStatementField(ms, "keyGenerator", Jdbc3KeyGenerator.INSTANCE);
    }

    // HACK: set MappedStatement.keyProperties with reflection
    private void setMappedStatementKeyProperties(MappedStatement ms, String[] keyProperties) throws NoSuchFieldException, IllegalAccessException {
        setMappedStatementField(ms, "keyProperties", keyProperties);
    }

    // HACK: set MappedStatement.keyColumns with reflection
    private void setMappedStatementKeyColumns(MappedStatement ms, String[] columns) throws NoSuchFieldException, IllegalAccessException {
        setMappedStatementField(ms, "keyColumns", columns);
    }

    private void setMappedStatementField(MappedStatement ms, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
        Field field = ms.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(ms, value);
    }
}
